<template>
  <div class="flex">
    <div class="w-full h-auto relative">
      <div
        ref="dropZoneRef"
        class="cursor-pointer"
        @click="() => {
          if (props.disabled) {
            return
          }
          open()
        }"
      >
        <div
          v-if="fileData.length === 0"
          class="d-flex flex-column justify-center align-center gap-y-2 pa-12 drop-zone rounded"
        >
          <IconBtn
            variant="tonal"
            class="rounded-sm"
          >
            <VIcon icon="tabler-upload" />
          </IconBtn>
          <h4 class="text-h4">
            支持拖拽图片文件
          </h4>
          <span class="text-disabled">or</span>

          <VBtn
            variant="tonal"
            size="small"
          >
            浏览图片文件
          </VBtn>
        </div>

        <div
          v-else
          class="d-flex justify-center align-center gap-3 pa-8 drop-zone flex-wrap"
        >
          <VRow class="match-height w-100">
            <template
              v-for="(item, index) in fileData"
              :key="index"
            >
              <VCol
                cols="12"
                sm="4"
              >
              <v-skeleton-loader
                :loading="item.loading"
                class="mx-auto border"
                style="display: block;height: 100%;"
                type="image, list-item-two-line"
              >
                <VCard :ripple="false">
                  <VCardText
                    class="d-flex flex-column"
                    @click.stop
                  >
                    <VImg
                      :src="item.url"
                      width="200px"
                      height="150px"
                      class="w-100 mx-auto"
                    />
                    <div class="mt-2" v-if="item.file">
                      <span class="clamp-text text-wrap">
                        {{ item.file?.name }}
                      </span>
                      <span>
                        {{ item.file?.size / 1000 }} KB
                      </span>
                    </div>
                  </VCardText>
                  <VCardActions>
                    <VBtn
                      variant="text"
                      block
                      :disabled="props.disabled"
                      @click.stop="remove(index)"
                    >
                      删除
                    </VBtn>
                  </VCardActions>
                </VCard>
              </v-skeleton-loader>
              </VCol>
            </template>
          </VRow>
        </div>
      </div>
    </div>
  </div>
</template>



<script setup>
import {
  useDropZone,
  useFileDialog,
  useObjectUrl,
} from '@vueuse/core'
import { uploadFile } from '@/utils';

const dropZoneRef = ref()
const fileData = ref([])
const {proxy } = getCurrentInstance()

const props = defineProps({
  modelValue:{
    type:Array,
    default:()=>[]
  },
  fileUrls:{
    type:Array,
    default:()=>[]
  },
  limit:{
    type:Number,
    default:6
  },
  disabled:{
    type:Boolean,
    default:false
  }
 })

 watch(
  () => props.fileUrls,
  async (val) => {
    fileData.value = val.map((item) => {
      return {
        url:item
      }
    })
    
  },
  { deep: true, immediate: true }
);

const event = defineEmits(['update:modelValue','update:fileUrls'])

const { open, onChange } = useFileDialog({ accept: 'image/*',reset:true })

const remove = (index) =>{
  fileData.value.splice(index, 1)
  event('update:modelValue',fileData.value)
  event('update:fileUrls',fileData.value.map(item=>item.url))
}

const upload = async (file)=>{
    // 生成唯一的标识符
    const uniqueId = Date.parse(new Date());

    // 先推入不带 ossUrl 和 ossId 的对象
    const fileEntry = {
      id: uniqueId,
      file,
      url: useObjectUrl(file).value ?? '',
      ossId: null,
      loading:true
    };
    fileData.value.push(fileEntry);
    const index = fileData.value.findIndex(entry => entry.id === uniqueId);
    // 上传文件
    const formData = new FormData();
    formData.append('file', file);
    const res = await uploadFile(formData).catch(err => {
      proxy.$toast.error("上传文件失败,请稍后再试")
      if (index !== -1) {
        fileData.value.splice(index, 1);
      }
    });
    // 更新对象
    if (index !== -1) {
      fileData.value[index] = {
        ...fileEntry,
        ossId: res.data.ossId,
        url: res.data.url,
        loading:false
      };
    }
    event('update:modelValue', fileData.value)
    const fileUrls = fileData.value.map(entry => entry.url)
    event('update:fileUrls', fileUrls)
    console.log(fileUrls)
}


function onDrop(DroppedFiles) {
  DroppedFiles?.forEach(file => {
    if (file.type.slice(0, 6) !== 'image/') {

      // eslint-disable-next-line no-alert
      alert('只允许上传图片文件')
      
      return
    }

    upload(file)
  })
}



onChange(async selectedFiles => {
  if (!selectedFiles)
    return
  for (const file of selectedFiles) {
    upload(file)
  }
})
useDropZone(dropZoneRef, onDrop)
</script>

<style lang="scss" scoped>
.drop-zone {
  border: 1px dashed rgba(var(--v-theme-on-surface), var(--v-border-opacity));
}
</style>
